import { Component, OnInit, OnChanges } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/modal-options.class';
import { CustomValidators } from './../../share/validators/custom-form.validators';
import { Subscription } from 'rxjs/Subscription';
import { ProductService } from './../../core/services/product.service';
import { ToasterService } from '../../share/toastr/toastr.service';
import { cbCfgList } from './../condition/condition-builder.config';


@Component({
  selector: 'app-modal-dailog',
  templateUrl: './modal-dailog.html',
  styleUrls: ['./modal-dailog.css'],
  providers: [BsModalService]
})
export class AddProductModalDailogComponent implements OnInit, OnChanges {

  form:          FormGroup;
  addProductSub: Subscription;

  formSubmit                       = false;
  productObj:               object = {};
  conditions:               any[]  = [];
  conditionsItemsOperation: any[]  = [];
  conditionsItemsValue:     any[]  = [];
  conditionsItemsCom:       any[]  = [];
  conditionSet:             any[]  = [];

  constructor(
    public  bsModalRef:     BsModalRef,
    private formBuilder:    FormBuilder,
    private productService: ProductService,
    public  toastrService:  ToasterService
  ) {  }

  ngOnInit() {
    this.initForm();
  }

  ngOnChanges() {
  }

  getConditionsItems(event) {
    this.conditions = event;
    console.log(this.conditions, '--- conditions from children ---');

    for (let i = 0; i < this.conditions.length; i++) {
      if (this.conditions[i].id == 0) {
        this.conditionSet.push({
          "id":        this.conditions[i].id,
          "value":     this.conditions[i].value,
          "operator":  this.conditions[i].operator,
          "component": this.conditions[i].com
        });
      } else if (this.conditions[i].id == 1) {
        this.conditionSet.push({
          "id":        this.conditions[i].id,
          "value":     this.conditions[i].value,
          "operator":  this.conditions[i].operator,
          "component": this.conditions[i].com
        });
      } else if (this.conditions[i].id == 2) {
        this.conditionSet.push({
          "id":        this.conditions[i].id,
          "value":     this.conditions[i].value,
          "operator":  this.conditions[i].operator,
          "component": this.conditions[i].com
        });
      } else if (this.conditions[i].id == 3) {
        this.conditionSet.push({
          "id":        this.conditions[i].id,
          "value":     this.conditions[i].value,
          "operator":  this.conditions[i].operator,
          "component": this.conditions[i].com
        });
      } else if (this.conditions[i].id == 4) {
        this.conditionSet.push({
          "id":        this.conditions[i].id,
          "value":     this.conditions[i].value,
          "operator":  this.conditions[i].operator,
          "component": this.conditions[i].com
        });
      } else if (this.conditions[i].id == 5) {
        this.conditionSet.push({
          "id":        this.conditions[i].id,
          "value":     this.conditions[i].value,
          "operator":  this.conditions[i].operator,
          "component": this.conditions[i].com
        });
      }
    }

    console.log('--- condition set ---', this.conditionSet);

  }

  getConditionsItemsOperators(event) {
    this.conditionsItemsOperation = event;
    console.log(this.conditionsItemsOperation, '--- conditions items operator from children ---');
  }

  getConditionsItemsVal(event) {
    this.conditionsItemsValue = event;
    console.log(this.conditionsItemsValue, '--- conditions items values from children ---');
  }

  getConditionsItemsCom(event) {
    this.conditionsItemsCom = event;
    console.log(this.conditionsItemsCom, '--- conditions items component from children ---');
  }


  initForm() {
    const asin = '';
    const tags = '';
    // CustomValidators.pattern(/^B[\dA-Z]{9}|\d{9}(X|\d)$/),
    this.form = this.formBuilder.group({
      'asin': [asin, Validators.compose([Validators.required, Validators.minLength(10)])]}, 
      {validator: this.ASINValidator('asin')});
  }

  ASINValidator(asins: string) {
    return (group: FormGroup): {[key: string]: any} => {
      const asin_amazon = group.controls[asins];
      if (!asin_amazon) {
        return {
          ASINError: true
        }
      } else if (asin_amazon.value.match(/^([A-Z0-9]{10})(\s*[\s\n,]\s*([A-Z0-9]{10}))*\s*$/) === null) {
        return {
          ASINError: true
        }
      }
    }
  }

  
  onSubmit() {
    const values    = this.form.value;
    const keys      = Object.keys(values);
    this.formSubmit = true;

    this.productObj = {
      "asin":      values.asin,
      "tags":      [],
      "conditions": this.conditions
    }

    console.log('condition set ---', this.conditionSet);

    console.log('conditions ---', this.conditions);

    console.log(`product object values : `, this.productObj);


    if (this.form.valid) {
      this.addProductSub  = this.productService.AddProduct(this.productObj)
          .subscribe(data => {
            const errors  = data.errors;
            console.log(`form data valid ...`);
            if (errors) {
              keys.forEach(val => {
                if (errors[val]) { 
                  this.pushError(val, errors);
                }
              });
            }
          });
          this.toastrService.successful('Add Product Successfuly !');
          this.bsModalRef.hide()
    } else {
      keys.forEach(val => {
        const ctrl = this.form.controls[val];
        if (!ctrl.valid) {
          this.pushError(val, null);
          ctrl.markAsTouched();
        }
      })
      this.toastrService.errors('Add Product Failed !');
    }
  }

  private pushError(ctrl_name: string, msg: string) {
    this.form.controls[ctrl_name].setErrors({'msg': msg});
  }

}
